package oaSystem.web.controller.rest;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import oaSystem.Exception.BizRunException;
import oaSystem.biz.FunctionBiz;
import oaSystem.biz.RoleBiz;
import oaSystem.entity.Function;
import oaSystem.entity.JsonResult;
import oaSystem.entity.Role;
import oaSystem.web.security.Authorize;

@Controller
@RequestMapping("/rest/role")
@RestController
public class Rest_RoleController {
	@Autowired
	public RoleBiz roleBiz;
	@Autowired
	public FunctionBiz functionBiz;
	
	/**
	 * 获取全部角色
	 * @return
	 */
	@Authorize(rules="security-list")
	@RequestMapping(value="",method=RequestMethod.GET)
	public List<Role> role(){
		List<Role> roleList = roleBiz.findAllRole();
		return roleList;
	}
	
	/**
	 * 获取角色信息（by roleID）
	 * @param roleId
	 * @return
	 */
	@Authorize(rules="security-edit")
	@RequestMapping(value="/update",method=RequestMethod.GET)
	public Role getRoleByRoleId(Integer roleId){
		return roleBiz.fetchRoleByRoleId(roleId);
	}
	
	/**
	 * 编辑角色
	 * @param name
	 * @param functionId
	 * @param roleId
	 * @return
	 */
	@Authorize(rules="security-edit")
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public JsonResult updateRole(String name,Integer[] functionId,Integer roleId){
		return editRole(functionId,name, roleId);
	}
	
	/**
	 * 增加角色
	 * @param name
	 * @param functionId
	 * @return
	 */
	@Authorize(rules="security-add")
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public JsonResult addRole(String name,Integer[] functionId){
		return editRole(functionId,name, null);
	}
	
	/**
	 * 方法抽取（保存/编辑角色）
	 * @param functionId
	 * @param roleId
	 * @return
	 */
	private JsonResult editRole(Integer[] functionId,String name, Integer roleId) {
		//新建FunctionList
		List<Function> functionList = new ArrayList<Function>();
		Function function=null;
		for (Integer id : functionId) {
			function=new Function(id);
			functionList.add(function);
		}
		
		//把functionList添加到role里面
		Role role = null;
		
		try {
			if(roleId!=null&&roleId>0){
				role = roleBiz.fetchRoleByRoleId(roleId);
				role.setFunctionAll(functionList);
				if(name!=null&&!name.isEmpty()){
					role.setName(name);
				}
				roleBiz.updateRole(role);
			}else{
				role = new Role(null, name);
				role.setFunctionAll(functionList);
				roleBiz.addRole(role);
			}
		} catch (BizRunException e) {
			return new JsonResult(false,e.getMessage());
		}
		return new JsonResult(true,null);
	}
}
